﻿using Csla.Core;
using Csla.Rules;
using System.Text.RegularExpressions;
using System;
using System.Collections;
using NetFrameworkExtensions.BusinessLayer.Csla4.Properties;

namespace NetFrameworkExtensions.BusinessLayer.Csla4.Rules
{
  public class NonEmptyListRule : PropertyRule
  {
    int minCount;

    public NonEmptyListRule(IPropertyInfo primaryProperty)
      : this(primaryProperty, 1)
    {
    }

    public NonEmptyListRule(IPropertyInfo primaryProperty, int minCount)
      : base(primaryProperty)
    {
      if (!typeof(IList).IsAssignableFrom(primaryProperty.Type))
        throw new ArgumentException("Property must accept IList values");

      if (minCount <= 0)
        throw new ArgumentOutOfRangeException("minCount", minCount, "min count must be greater than 0");

      this.minCount = minCount;
    }

    protected override void Execute(RuleContext context)
    {
      var list = ReadProperty(context.Target, PrimaryProperty) as IList;
      if (list != null)
      {
        if (list.Count < minCount)
        {
          var msg = string.Format(GetMessage(), PrimaryProperty.FriendlyName, minCount);
          context.AddErrorResult(PrimaryProperty, msg);
        }
      }
    }

    protected override string GetMessage()
    {
      if (!base.HasMessageDelegate)
        return FormattedResources.ExListCannotBeEmpty(PrimaryProperty.FriendlyName, minCount);
      return MessageText;
    }
  }
}
